package nero.yncc.com.createart.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import org.json.JSONException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;

import nero.yncc.com.createart.R;
import nero.yncc.com.createart.adapter.AdapteGoodDetailList;
import nero.yncc.com.createart.adapter.AdapterDetailChangjing;
import nero.yncc.com.createart.adapter.AdapterGoodsComment;
import nero.yncc.com.createart.base.BaseActivity;
import nero.yncc.com.createart.base.Constants;
import nero.yncc.com.createart.bean.BeanGoodsComment;
import nero.yncc.com.createart.bean.ChangjingBean;
import nero.yncc.com.createart.bean.GodBean;
import nero.yncc.com.createart.custom.IconView;
import nero.yncc.com.createart.fragment.FragmentGoodsDetail;
import nero.yncc.com.createart.interfaces.InterfaceDoSomeThing;
import nero.yncc.com.createart.utils.ArrayUtils;
import nero.yncc.com.createart.utils.CollectionUtil;
import nero.yncc.com.createart.utils.HttpUtils;
import nero.yncc.com.createart.utils.PopGuige;
import nero.yncc.com.createart.utils.ShareUtil;
import nero.yncc.com.createart.utils.TextUtil;


/**
 * Created by nero on 2017/6/26.
 */

@ContentView(R.layout.activity_god_detail)
public class ActivityGoodDetail extends BaseActivity {

    @ViewInject(R.id.vp_main)
    ViewPager vp_main;
    @ViewInject(R.id.tv_title)
    TextView tv_title;
    @ViewInject(R.id.tv_attr)
    TextView tv_attr;

    @ViewInject(R.id.ll_dom)
    LinearLayout ll_dom;

    @ViewInject(R.id.rl_dom)
    RelativeLayout rl_dom;
    @ViewInject(R.id.rc_list)
    ListView rc_list;
    @ViewInject(R.id.tv_num2)
    TextView tv_num2;
    @ViewInject(R.id.icon_back_huanneng)
    IconView icon_back_huanneng;


    View view_red;


    @ViewInject(R.id.tv_price)
    TextView tv_price;
    @ViewInject(R.id.tv_salenum)
    TextView tv_salenum;
    @ViewInject(R.id.tv_comment_num)
    TextView tv_comment_num;
    @ViewInject(R.id.rl_comment)
    RelativeLayout rl_comment; //评论点击 作用查看所有评论


    @ViewInject(R.id.wv_123)
    WebView wv_123;
    @ViewInject(R.id.btn_addShopCar)
    Button btn_addShopCar;

    @ViewInject(R.id.rl_choose_spec)
    RelativeLayout rl_choose_spec;
    @ViewInject(R.id.tv_price_all)
    TextView tv_price_all;
    @ViewInject(R.id.rl_choose_zuhe)
    RelativeLayout rl_choose_zuhe;
    @ViewInject(R.id.tv_youhuiNum)
    TextView tv_youhuiNum;

    @ViewInject(R.id.icon_share)
    IconView icon_share;
    @ViewInject(R.id.icon_shopcar)
    IconView icon_shopcar;
    @ViewInject(R.id.icon_collection)
    IconView icon_collection;
    @ViewInject(R.id.ll_comment)
    LinearLayout ll_comment;

    @ViewInject(R.id.rl_needknow)
    RelativeLayout rl_needknow;

    GodBean godBean;

    ArrayList<GodBean.ImageUrl> arrayList_image;

    String id = "";
    GodBean.Goods goods;
    AdapterGoodsComment adapterGoodsComment;
    ArrayList<BeanGoodsComment> arr_comment;

    @Override
    protected void initData() {
        super.initData();
        id = getIntent().getStringExtra("id");
        arrayList_image = new ArrayList<>();
        arr_comment = new ArrayList<>();
        setStateBarColor(R.color.translate);

        adapterGoodsComment = new AdapterGoodsComment(mContext, arr_comment);
        rc_list.setAdapter(adapterGoodsComment);

    }

    @Override
    protected void initView() {
        super.initView();
//        byScroll(true);
    }

    int page = 5;

    private void initViewPager() {
        if (page > 1) {
            for (int a = 0; a < page; a++) {
                View views = LinearLayout.inflate(mContext, R.layout.view_dom, null);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(9, 9);
                params.setMargins(5, 5, 5, 5);
                views.setBackgroundResource(R.drawable.tv_dom_white);
                views.setLayoutParams(params);
                ll_dom.addView(views);
            }

            view_red = LinearLayout.inflate(mContext, R.layout.view_dom, null);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(9, 9);
            params.setMargins(5, 5, 5, 5);
            view_red.setLayoutParams(params);
            view_red.setBackgroundResource(R.drawable.tv_dom_yellow);
            params.addRule(RelativeLayout.ALIGN_LEFT, R.id.ll_dom);
            rl_dom.addView(view_red);
        }
        vp_main.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view_red.getLayoutParams();
                //70为一个

                params.setMargins((int) (19 * (positionOffset) + 19 * position) + 5, 5, 5, 5);
                view_red.setLayoutParams(params);
                view_red.setBackgroundResource(R.drawable.tv_dom_yellow);
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        vp_main.setAdapter(new FragmentPagerAdapter(this.getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                FragmentGoodsDetail fragmentGoodsDetail = new FragmentGoodsDetail();

                Bundle bundle = new Bundle();
                bundle.putSerializable("url", arrayList_image.get(position).getImage_url());
                fragmentGoodsDetail.setArguments(bundle);
                return fragmentGoodsDetail;
            }

            @Override
            public int getCount() {
                return page;
            }
        });
    }

    int taozhuangNum = 0;

    @Override
    protected void getHttpData() {
        super.getHttpData();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("id", id);
        hashMap.put("user_id", userBean.getUser_id());
        new HttpUtils().post(this, Constants.API_GOODSINFO, hashMap, GodBean.class, HttpUtils.TYPE_OBJECT, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                godBean = (GodBean) json;
                //初始化ViewPager
                ArrayUtils.copy(godBean.getGallery(), arrayList_image, true);
                page = arrayList_image.size();
                initViewPager();
                //初始化商品参数
                goods = godBean.getGoods();
                tv_title.setText(TextUtil.getText(goods.getGoods_name(), "暂无名称"));
                tv_attr.setText(TextUtil.getText(goods.getGoods_remark(), "暂无简介"));
                tv_price.setText("￥" + TextUtil.getText(goods.getShop_price(), "0"));
                tv_price_all.setText("￥" + TextUtil.getText(goods.getShop_price(), "0"));
                tv_salenum.setText(TextUtil.getText(goods.getSales_sum(), "0"));
                tv_comment_num.setText(TextUtil.getText(goods.getComment_count(), "0"));
                tv_num2.setText("(" + TextUtil.getText(goods.getComment_count(), "0") + ")");
                wv_123.loadData(goods.getGoods_content(), "text/html", "utf-8");
                String taozhuang = goods.getTaozhuang();
                if (!TextUtils.isEmpty(taozhuang)) {
                    String[] arr = taozhuang.split("\\{");
                    taozhuangNum = arr.length - 2;
                }
                if (taozhuangNum < 0)
                    taozhuangNum = 0;

                if (taozhuangNum == 0) {
                    rl_choose_zuhe.setVisibility(View.GONE);
                } else {
                    tv_youhuiNum.setText(taozhuangNum + "个组合套装");
                }
                if (goods.getIcollect().equals("1")) {
                    icon_collection.setTextColor(getResources().getColor(R.color.project_yellow));
                }
                getComment();
            }

            @Override
            public void fail(String failMsg) {
                showToast(failMsg);
            }
        });
//

    }

    private void getComment() {
        //获取评论列表 取出3条就够咯
        HashMap<String, String> hashMap_comment = new HashMap<>();
        hashMap_comment.put("goods_id", id);
        hashMap_comment.put("p", "1");
        new HttpUtils().post(this, Constants.API_GOODSCOMMENT, hashMap_comment, null, HttpUtils.TYPE_ARRAY, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                org.json.JSONArray jsonArray = (org.json.JSONArray) json;
                if (jsonArray == null || jsonArray.length() == 0) {
                    ll_comment.setVisibility(View.VISIBLE);
                    rc_list.setVisibility(View.GONE);
                    return;
                }

                for (int a = 0; a < jsonArray.length(); a++) {
                    BeanGoodsComment beanGoodsComment = null;
                    try {
                        beanGoodsComment = JSON.parseObject(jsonArray.getString(a), BeanGoodsComment.class);
                        if (arr_comment.size() < 3)
                            arr_comment.add(beanGoodsComment);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                adapterGoodsComment.notifyDataSetChanged();
                setListViewHeightBasedOnChildren(rc_list);
            }

            @Override
            public void fail(String failMsg) {
//                showToast(failMsg);
            }
        });
    }

    @Override
    protected void initListener() {
        super.initListener();
        rl_comment.setOnClickListener(this);// 查看所有评论
        btn_addShopCar.setOnClickListener(this);//选择规格
        rl_choose_spec.setOnClickListener(this);//选择规格
        rl_choose_zuhe.setOnClickListener(this);//选择组合
        icon_back_huanneng.setOnClickListener(this);

        icon_share.setOnClickListener(this);
        icon_collection.setOnClickListener(this);
        icon_shopcar.setOnClickListener(this);

        ll_comment.setOnClickListener(this);
        rl_needknow.setOnClickListener(this);
    }

    PopGuige popGuige;

    @Override
    protected void doClick(int id) {
        super.doClick(id);
        switch (id) {
            case R.id.rl_comment:
            case R.id.ll_comment:
                Intent intent = new Intent(mContext, ActivityComment.class);
                intent.putExtra("id", goods.getGoods_id());
                startActivity(intent);
                break;
            case R.id.icon_share:
                ShareUtil.share(mContext);
                break;
            case R.id.icon_collection:
                if (goods.getIcollect().equals("0")) {
                    CollectionUtil.collection(this, goods.getGoods_id(), userBean, CollectionUtil.collection, new InterfaceDoSomeThing() {
                        @Override
                        public void doSomething(String some) {
                            super.doSomething(some);
                            goods.setIcollect("1");
                        }
                    });
                } else {
                    CollectionUtil.collection(this, goods.getGoods_id(), userBean, CollectionUtil.cancel, new InterfaceDoSomeThing() {
                        @Override
                        public void doSomething(String some) {
                            super.doSomething(some);
                            goods.setIcollect("1");
                        }
                    });
                }

                break;
            case R.id.icon_shopcar:
                startActivity(new Intent(mContext, ActivityShopcar.class));
                break;

            case R.id.icon_back_huanneng:
                finish();
                break;
            case R.id.rl_choose_spec:
                if (godBean.getGoods().getGoods_spec_list().size() <= 0) {
                    showToast("该商品没有规格");
                    return;
                }
                popGuige = new PopGuige(mContext, godBean, userBean);
                popGuige.show(this);
                break;
            case R.id.btn_addShopCar:
//                if (godBean.getGoods().getGoods_spec_list().size() <= 0) {
//                    showToast("该商品没有规格");
//                    return;
//                }
                try {
                    if (Integer.parseInt(godBean.getGoods().getStore_count()) <= 0) {
                        showToast("该商品库存不足 无法下单");
                        return;
                    }
                } catch (NumberFormatException e) {
                    showToast("该商品库存不足 无法下单");
                    return;
                }

                popGuige = new PopGuige(mContext, godBean, userBean);
                popGuige.show(this);
                break;
            case R.id.rl_choose_zuhe:
                if (goods == null) {
                    showToast("该商品信息不完整");
                    return;
                }
                Intent intent_taozhuang = new Intent(mContext, ActivityTaozhuang.class);
                intent_taozhuang.putExtra("id", goods.getGoods_id());
                startActivity(intent_taozhuang);
                break;
            case R.id.rl_needknow:
                showToast("暂未添加该内容");
                return;
//                String type_id=Constants.hashmap_type.get("购买须知");
//                if(TextUtils.isEmpty(type_id)){
//                    showToast("暂未添加该内容");
//                    return;
//                }
//                break;
        }
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {

        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;

        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10); // 可删除

        listView.setLayoutParams(params);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            try {
                if (popGuige == null || popGuige.isShow()) {
                    popGuige.disMiss();
                    return true;
                }
            } catch (Exception e) {
            }

        }
        return super.onKeyDown(keyCode, event);
    }
}
